import { inject } from "vue";

export const useFileOperation = () => {
    let API = inject("API") as any;
    let ApiConfig = inject("ApiConfig") as any;

    //文件下载
    const downloadFile = async (objectId, fileName) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.File.Download,
                {
                    objectId: objectId,
                    fileName: fileName
                },
                {
                    'Accept': 'application/octet-stream', // 确保接受流数据
                },
                'blob',// 设置 responseType 为 'blob'
            );

            if (response.status == "200") {
                const blob = response.data;

                // 创建 URL 对象
                const fileURL = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = fileURL;
                link.download = fileName;

                // 触发点击事件以下载文件
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // 释放 URL 对象
                window.URL.revokeObjectURL(fileURL);
            }
        } catch (error) {
            console.error(error);
        }
    }

    // 删除文件的处理函数
    const deleteFile = async (objectId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.File.Delete,
                { objectId: objectId }
            );
            if (response.status == "200" && response.data.code == "200") {
                // 文件删除成功，触发事件通知父组件
                return true
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }

    return { downloadFile, deleteFile }
}